1375D - Replace by MEX - CodeForces Solution


brute force constructive algorithms sortings *1900

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define mp make_pair
#define all(x) x.begin(),x.end()
 
int main()
{
	ll t;
	cin>>t;
	read:
	while(t--){
		ll n;
		cin>>n;
 
		ll id[n+1],a[n+1];
		memset(id,0,sizeof(id));
		set<ll> m;
		vector<ll> ans;
		for(ll i=1;i<=n;i++){
			cin>>a[i];
			id[a[i]]++;
		}
		for(ll i=0;i<=n;i++){
			if(!id[i]) m.insert(i);
		}
 
		ll mx=n;
		while(1){
			ll mex=*m.begin();
			m.erase(m.begin());
			id[mex]++;
			if(mex!=mx){
				id[a[mex+1]]--;
				if(!id[a[mex+1]]) m.insert(a[mex+1]);
				a[mex+1]=mex;
				ans.pb(mex+1);
			}
			else{
				if(!mex) break;
				mx--;
				id[a[mex]]--;
				if(!id[a[mex]]) m.insert(a[mex]);
				a[mex]=mex;
				ans.pb(mex);
			}
			if(!mx) break;
		}
 
		cout<<ans.size()<<endl;
		for(ll i=0;i<ans.size();i++) cout<<ans[i]<<" ";cout<<endl;
	}

    return 0;
}


Comments

Submit
0 Comments
More Questions

1644A - Doors and Keys
1644B - Anti-Fibonacci Permutation
1610A - Anti Light's Cell Guessing
349B - Color the Fence
144A - Arrival of the General
1106A - Lunar New Year and Cross Counting
58A - Chat room
230A - Dragons
200B - Drinks
13A - Numbers
129A - Cookies
1367B - Even Array
136A - Presents
1450A - Avoid Trygub
327A - Flipping Game
411A - Password Check
1520C - Not Adjacent Matrix
1538B - Friends and Candies
580A - Kefa and First Steps
1038B - Non-Coprime Partition
43A - Football
50A - Domino piling
479A - Expression
1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy